<?php
	namespace Common\Logic;
	use Common\Model\OrdersModel;
	class OrdersLogic extends OrdersModel{
		/*
		* Function:		getOrdersList
		* Description:	订单列表
		* @param:		$page string 起始页
						$filter array 过滤数组
						$pageSize string 每页显示条数
		*/
		public function getOrdersList($page=1,$filter = '',$pageSize=20){
			$conditon = $this->getOrdersFilter($filter);
			return $this->where($conditon)->order('id desc')->limit(($page-1)*$pageSize,$pageSize)->select();
		}
		
		/*
		* Function:get:	getOrdersFilter
		* Description:	订单列表搜索过滤项
		* @param:		$filter array 过滤数组
		*/
		public function getOrdersFilter($filter = ''){
			$conditon = array();
			if(!empty($filter['order_id'])){
				$conditon['order_id'] = $filter['order_id'];
			}
			if(!empty($filter['status'])){
				$conditon['status'] = $filter['status'];
			}
			if(!empty($filter['user_id'])){
				$conditon['user_id'] = $filter['user_id'];
			}
			if(!empty($filter['status'])){
				$conditon['status'] = $filter['status'];
			}
			if($filter['sync_status'] != ''){
				$conditon['sync_status'] = $filter['sync_status'];
			}
			if(!empty($filter['user_name'])){
				$wh = array();
				$wh['username'] = array('like','%'.$filter['user_name'].'%');
				$sql = D('User')->field('id')->where($wh)->select(false);
				$conditon['user_id'] = array('exp','in('.$sql.')');
			}
			if(!empty($filter['addtime_fromdate']) || !empty($filter['addtime_todate'])){
				if(!empty($filter['addtime_fromdate']) && !empty($filter['addtime_todate'])){
					$conditon['addtime'] = array(array('egt',$filter['addtime_fromdate']),array('elt',$filter['addtime_todate']));
				}else if(!empty($filter['addtime_fromdate'])){
					$conditon['addtime'] = array('egt',$filter['addtime_fromdate']);
				}else if(!empty($filter['addtime_todate'])){
					$conditon['addtime'] = array('elt',$filter['addtime_todate']);
				}
			}
			return $conditon;
		}
		
		/*
		* Function:get:	getOrdersCount
		* Description:	订单列表总数
		* @param:		$filter array 过滤数组
		*/
		public function getOrdersCount($filter = ''){
			$conditon = $this->getOrdersFilter($filter);
			return $this->where($conditon)->count();
		}
		
		/*
		* Function:		addOrders
		* Description:	增加订单
		* @param:		$data array 增加的数组
		*/
		public function addOrders($data){
			return $this->add($data);
		}
		
		/*
		* Function:		getOrdersInfo
		* Description:	获取订单信息 by row
		* @param:		$id int ID
		*/
		public function getOrdersInfo($id){
			return $this->where(array('id'=>$id))->find();
		}
		
		/*
		* Function:		getOrdersInfoByOrderId
		* Description:	获取订单信息 by row
		* @param:		$id int ID
		*/
		public function getOrdersInfoByOrderId($order_id){
			return $this->where(array('order_id'=>$order_id))->find();
		}
		
		/*
		* Function:		updateOrders
		* Description:	更新订单
		* @param:		$data array 更新的数组
		*/
		public function updateOrders($data){
			return $this->save($data);
		}
		
		/*
		* Function:		deleteOrders
		* Description:	删除订单
		* @param:		$id int ID
		*/
		public function deleteOrders($id){
			return $this->where(array('id'=>$id))->delete();
		}
		
		/*
		* Function:		getOrdersAllList
		* Description:	获取全部订单列表
		*/
		public function getOrdersAllList(){
			return $this->where(array('status'=>1))->select();
		}

		/*
		* Function:		directBuyOrder
		* Description:	订单直接购买
		*/
		public function directBuyOrder($data){
			$return = [];
			$goodsData = [];
			//判断商品是否上架
			if($goodsInfo = M('goods')->where(['id'=>$data['goods_id']])->find()){
				if(empty($goodsInfo['status'])){
					return ['code'=>0,'errorMsg'=>'商品已下架'];
				}
			}else{
				return ['code'=>0,'errorMsg'=>'不存在此商品'];
			}
			if(empty($data['goods_spec_id'])){
				$goodsListInfo = M('goods_list')->where(['id'=>$data['goods_list_id']])->find();
			}else{
				$goodsListInfo = M('goods_list')->where(['goods_id'=>$data['goods_id'],'goods_spec_id'=>$data['goods_spec_id']])->find();
			}
			if(!empty($goodsListInfo)){
				if(empty($goodsListInfo['status'])){
					return ['code'=>0,'errorMsg'=>'此商品规格已下架'];
				}
			}else{
				return ['code'=>0,'errorMsg'=>'此商品规格不存在'];
			}
			if($data['nums']<=0){
				return ['code'=>0,'errorMsg'=>'商品数量有误'];
			}
			//判断商品库存是否够
			if(($goodsListInfo['stocks']-$goodsListInfo['freez']-$data['nums'])<0){
				return ['code'=>0,'errorMsg'=>'商品库存不足'];
			}
			if(empty($goodsListInfo['goods_img_url'])){
				$goodsListInfo['goods_img_url'] = $goodsInfo['goods_small_pic'];
			}
			$goodsData = [['goods_id'=>$data['goods_id'],'goods_list_id'=>$data['goods_list_id'],'goods_spec_id'=>$data['goods_spec_id'],'num'=>$data['nums'],'size'=>$goodsListInfo['goods_spec'],'prize'=>$goodsListInfo['selling_price'],'img'=>$goodsListInfo['goods_img_url'],'isSelected'=>true,'name'=>$goodsInfo['goods_title'],'integral'=>$goodsInfo['integral']]];
			return ['code'=>1,'errorMsg'=>'success','data'=>$goodsData];
		}

		/*
		* Function:		addUserOrders
		* Description:	用户增加订单
		*/
		public function addUserOrders($data){
			$return = [];
			$dataList = [];
			$goodsSql = [];
			$dateTime = date('Y-m-d H:i:s',time());
			$ordersData = [];
			$total_nums = 0;
			$product_amount = 0;
			$ordersData['order_id'] = $this->generateOrderId('YR');
			$ordersData['user_id'] = $data['user_id'];
			$ordersData['total_integral'] = $data['total_integral'];
			$this->startTrans();
			$coupon_amount = $data['coupon_amount'];
			$is_full_coupon = 0;
			if(!empty($data['coupon_id'])){
				if($couponInfo = M('user_coupon')->where(['tid'=>$data['coupon_id'],'user_id'=>$data['user_id']])->find()){
					if($couponInfo['status']!=0){
						return ['code'=>0,'errorMsg'=>'优惠券已使用或者已过期'];
					}else{
						if((time()-strtotime($couponInfo['validity_end_time']))>0){
							return ['code'=>0,'errorMsg'=>'优惠券已过期'];
						}
					}
				}else{
				    if($couponInfo = M('coupons')->where(['id'=>$data['coupon_id'],'cate'=>2,'is_deleted'=>0])->find()){//全场
				        $is_full_coupon = 1;
				        if($couponInfo['status']!=0){
    						return ['code'=>0,'errorMsg'=>'优惠券已使用或者已过期'];
    					}else{
    						if((time()-strtotime($couponInfo['validity_end_time']))>0){
    							return ['code'=>0,'errorMsg'=>'优惠券已过期'];
    						}
    					}
				    }else{
				        return ['code'=>0,'errorMsg'=>'优惠券已失效'];
				    }
				}
			}
			if(is_array($data['goods_data'])&&count($data['goods_data'])>0){
				foreach($data['goods_data'] as $key=>$val){
				    $val['nums'] = $val['num'];
				    $val['price'] = $val['prize'];
					//判断商品是否上架
					$sData = [];
					$goodsInfo = M('goods')->where(['id'=>$val['goods_id']])->find();
					if(!empty($goodsListInfo['goods_spec_id'])){
						$goodsListInfo = M('goods_list')->where(['goods_id'=>$val['goods_id'],'goods_spec_id'=>$val['goods_spec_id']])->find();
					}else{
						$goodsListInfo = M('goods_list')->where(['goods_id'=>$val['goods_id']])->find();
					}
					if($val['nums']<=0){
						return ['code'=>0,'errorMsg'=>'商品数量有误'];
					}
					//判断商品库存是否够
					if(($goodsListInfo['stocks']-$goodsListInfo['freez']-$val['nums'])<0){
						return ['code'=>0,'errorMsg'=>'商品库存不足'];
					}
					$sData['order_id'] = $ordersData['order_id'];
					$sData['user_id'] = $data['user_id'];
					$sData['goods_id'] = $val['goods_id'];
					$sData['goods_list_id'] = $val['goods_list_id'];
                    $sData['goods_spec_id'] = $val['goods_spec_id'];
					$sData['price'] = $val['price'];
					$sData['nums'] = $val['nums'];
					$sData['amount'] = $val['price']*$val['nums'];
					$sData['goods_spec'] = $goodsListInfo['goods_spec'];
					$sData['goods_title'] = $goodsInfo['goods_title'];
					$sData['addtime'] = $dateTime;
					$dataList[] = $sData;
					$total_nums += $val['nums'];
					$product_amount += $val['nums']*$val['price'];
					//清空购物车
			      M('order_cart')->where(['type'=>1,'user_id'=>$data['user_id'],'goods_id'=>$val['goods_id'],'goods_spec_id'=>$val['goods_spec_id']])->delete();
				}
			}else{
				return ['code'=>0,'errorMsg'=>'缺少商品参数'];
			}
			if(empty($data['user_addr_id'])){
				return ['code'=>0,'errorMsg'=>'缺少收货地址'];
			}
			if(!$userAddrInfo = M('user_addr')->where(['id'=>$data['user_addr_id']])->find()){
				return ['code'=>0,'errorMsg'=>'收货地址不存在'];
			}
			$orderAddr = [];
			$orderAddr['order_id'] = $ordersData['order_id'];
			$orderAddr['user_id'] = $data['user_id'];
			$orderAddr['ship_name'] = $userAddrInfo['ship_name'];
			$orderAddr['ship_mobile'] = $userAddrInfo['phone'];
			$orderAddr['province_id'] = $userAddrInfo['province_id'];
			$orderAddr['province'] = $userAddrInfo['province'];
			$orderAddr['city_id'] = $userAddrInfo['city_id'];
			$orderAddr['city'] = $userAddrInfo['city'];
			$orderAddr['area_id'] = $userAddrInfo['area_id'];
			$orderAddr['area'] = $userAddrInfo['area'];
			$orderAddr['address'] = $userAddrInfo['address'];
			$orderAddr['addtime'] = $dateTime;
			//主订单数据信息
			$ordersData['total_nums'] = $total_nums;
			$ordersData['product_amount'] = $product_amount;
			$ordersData['discount_price'] = $coupon_amount;
			$ordersData['total_amount'] = $product_amount-$coupon_amount;
			$ordersData['currency'] = 1;
			$ordersData['status'] = 1;
			$ordersData['addtime'] = $dateTime;
			$ret = $this->addOrders($ordersData);
			if(empty($ret)){
				$this->rollback();
				return ['code'=>0,'errorMsg'=>'生成订单失败'];
			}
			if(is_array($dataList)&&count($dataList)>0){
            if(count($dataList)>1){
               foreach($dataList as $key=>$val){
                  //M('goods')->where(['id'=>$val['goods_id']])->setInc('freez',$val['nums']);
                  if(!empty($val['goods_spec_id'])){
                     M('goods_list')->where(['goods_id'=>$val['goods_id'],'goods_spec_id'=>$val['goods_spec_id']])->setInc('freez',$val['nums']);
                  }else{
                     M('goods_list')->where(['goods_id'=>$val['goods_id']])->setInc('freez',$val['nums']);
                  }
               }
            }
			}else{
			    $this->rollback();
				return ['code'=>0,'errorMsg'=>'缺少订单明细参数'];
			}
			$ret = M('order_list')->addAll($dataList);
			if(empty($ret)){
				$this->rollback();
				return ['code'=>0,'errorMsg'=>'生成订单明细失败'];
			}
			$ret = M('order_address')->add($orderAddr);
			if(empty($ret)){
				$this->rollback();
				return ['code'=>0,'errorMsg'=>'生成订单地址失败'];
			}
			//更改优惠券已使用
			if(!empty($is_full_coupon)){
			    $couponData = [];
			    $couponData['cate'] = 2;
			    $couponData['type'] = $couponInfo['type'];
			    $couponData['user_id'] = $data['user_id'];
			    $couponData['order_id'] = $ordersData['order_id'];
			    $couponData['condition_amount'] = $couponInfo['condition_amount'];
			    $couponData['coupon'] = $couponInfo['coupon'];
			    $couponData['validity_begin_time'] = $couponInfo['validity_begin_time'];
			    $couponData['validity_end_time'] = $couponInfo['validity_end_time'];
			    $couponData['addtime'] = date('Y-m-d H:i:s',time());
			    M('user_coupon')->add($couponData);
			}else{
    			$ret = M('user_coupon')->where(['tid'=>$data['coupon_id'],'user_id'=>$data['user_id']])->save(['status'=>1,'order_id'=>$ordersData['order_id']]);
    			if($ret===false){
    				$this->rollback();
    				return ['code'=>0,'errorMsg'=>'优惠券状态更新失败'];
    			}
			}
			//增加商品库存冻结
			$this->commit();
			return ['code'=>1,'errorMsg'=>'success','order_id'=>$ordersData['order_id'],'price'=>$ordersData['total_amount']];
		}

		/*
		* Function: generateOrderId
		* Description:生成唯一订单号
		* @param:$supplierCode string 商家编码orcode
		*/
		public function generateOrderId($code = ''){
			$order_id = $code.date('YmdHis',time()).rand(10000,99999);
			if($this->getOrdersInfoByOrderId($order_id)){
				return $this->generateOrderId($code);
			}
			return $order_id;
		}
		
		/*
		* 获取订单状态
		*/
		public function getOrderStatusList(){
			return array(
				array('name'=>'待支付','value'=>'1'),
				array('name'=>'待发货','value'=>'2'),
				array('name'=>'已发货','value'=>'3'),
				array('name'=>'已收货','value'=>'4'),
				array('name'=>'已取消','value'=>'5'),
				array('name'=>'待退款','value'=>'6')
			);
		}
	}
?>